package org.example.hello6_MessageConfirmation;

import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class WatchMessageImpl implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnsCallback {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void initRabbitTemplate(){
        rabbitTemplate.setReturnsCallback(this);
        rabbitTemplate.setConfirmCallback(this);
    }


    /**
     * 当消息到达交换机之后触发（到达交换机之后，该方法会被回调）
     *
     * @param correlationData 相关数据
     * @param ack             交换机接收消息是否成功
     * @param cause           如果没有成功，返回原因
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        if (ack) {
            System.out.println("交换机接收消息成功");
        } else {
            System.out.println("交换机接收消息失败,失败原因是：" + cause);
        }
    }


    /**
     * 消息如果未正常到达队列里面 会回调
     *
     * @param returnedMessage 消息内容  回调相应码  响应文本  交换机  路由key
     */
    @Override
    public void returnedMessage(ReturnedMessage returnedMessage) {
        System.out.println("队列未接收到消息");
        System.out.println("ReplyText:" + returnedMessage.getReplyText());
        System.out.println("RoutingKey:" + returnedMessage.getRoutingKey());
        System.out.println("ReplyCode:" + returnedMessage.getReplyCode());
        System.out.println("Message:" + returnedMessage.getMessage());

    }
}

